import SQLiteParser
from physical import *

emails = list()
accounts = dict()
attachments = dict()
folders = dict()

for fs in ds.FileSystems:
	for f in fs.Search('com.outlook.Z7/databases/email.db'):
		if f.AbsolutePath.endswith('email.db'):
			node = f
			db = SQLiteParser.Database.FromNode(f)
			
			for record in db.ReadTableRecords('accounts'):
				accounts[record['account_id'].Value] = record['user_name'].Value
			
			for record in db.ReadTableRecords('folders'):
				folders[record['_id'].Value]=record['name'].Value	
				
			for record in db.ReadTableRecords('emails'):
				email = Email()
				email.Account.Value = accounts[record['account_id'].Value]
				email.Source.Value = 'Outlook Mail'
				email.Folder.Value = folders[record['folder_id'].Value]
				subject = record['subject'].Value
				if type(subject) == str:
					email.Subject.Value = subject
				email.TimeStamp.Value = TimeStamp.FromUnixTime(int(record['delivery_time'].Value)/1000)
				email.From.Value = Party.MakeFrom(record['_from'].Value,None)
				tos = record['_to'].Value
				if type(tos) == str:
					for to_addresses in tos.split(','):
						email.To.Add(Party.MakeTo(to_addresses,None))
				tos = record['cc'].Value
				if type(tos) == str:
					for to_addresses in tos.split(','):
						email.Cc.Add(Party.MakeTo(to_addresses,None))
				if type(tos) == str:
					for to_addresses in tos.split(','):
						email.To.Add(Party.MakeTo(to_addresses,None))
				body_html = record['html_body'].Value
				if type(body_html) == str:
					email.Body.Value = body_html
				else:
					email.Body.Value = record['body'].Value
				emails.append(email)
				
			
ds.Models.AddRange(emails)